package com.zyz.forum.controller;

import com.zyz.forum.common.AppResult;
import com.zyz.forum.common.ResultCode;
import com.zyz.forum.config.AppConfig;
import com.zyz.forum.exception.ApplicationException;
import com.zyz.forum.model.User;
import com.zyz.forum.service.IUserService;
import com.zyz.forum.utils.Md5Util;
import com.zyz.forum.utils.StringUtil;
import com.zyz.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat)
            throws ApplicationException {
        // 以上通过@NonNull确保不为空
        // 进行确认密码的验证
        if (!password.equals(passwordRepeat)) {
            // 打印日志
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //controller层一般不抛异常，直接返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 创建user对象进行新增用户
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 创建盐值
        String salt = UUIDUtil.UUID_32();
        user.setSalt(salt);
        // 加密密码
        String encipher = Md5Util.md5Salt(password,salt);
        user.setPassword(encipher);
        // 调用service层
        userService.createNormalUser(user);
        // 成功
        return AppResult.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        // 调用service层登录方法
        User user = userService.login(username,password);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 把user对象放入session中
        HttpSession session = request.getSession(true); // 如果没有session对象就创建
        session.setAttribute(AppConfig.USER_SESSION_ID,user);
        // 返回成功结果
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/userInfo")
    public AppResult<User> getUserInfo (HttpServletRequest request,
                                        @ApiParam("用户id") @RequestParam(value = "id",required = false) Long userId) {
        User user = null;
        if (userId == null) {
            // 1.从session中获取用户信息
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute(AppConfig.USER_SESSION_ID) == null) {
                log.warn(ResultCode.FAILED_FORBIDDEN.toString());
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            // session内容存在
            user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
            // 返回user信息
            return AppResult.success(user);
        }
        // 2.id不为空，通过id查找用户信息
        user = userService.selectById(userId);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 返回查询结果
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        // 判断session是否有效
        if (session != null) {
            // 表示再登录状态，直接销毁session
            session.invalidate();
            // 打印日志
            log.info("退出成功.");
        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username" ,required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname" ,required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender" ,required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email" ,required = false) String email ,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum" ,required = false) String phoneNum ,
                                @ApiParam("个人简介") @RequestParam(value = "remark" ,required = false) String remark) {
        // 参数校验，如果都为空返回错误描述
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
            && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
            && StringUtil.isEmpty(remark) && gender == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed("请输入要修改的内容");
        }
        // 从session中获取userId
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        // 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        // 调用service层
        userService.updateUserInfo(updateUser);
        // 查询最新用户信息
        user = userService.selectById(user.getId());
        // 把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION_ID,user);
        // 不报错代表成功
        log.info("修改信息成功！");
        return AppResult.success(user);
    }

    @RequestMapping(value = "/editAvatarUrl",method = RequestMethod.POST)
    public AppResult<Void> editAvatarUrl (HttpServletRequest request , @RequestPart("file") MultipartFile file) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        userService.editAvatarUrl(user,file);
        return AppResult.success();
    }



    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 获取session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        // 判断确认密码是否和新密码相同
        if (!newPassword.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 调用service层
        userService.modifyPassword(user.getId(),oldPassword,newPassword);
        // 销毁session，使用新密码登录
        session.invalidate();
        // 返回正确信息，并打印
        log.info("修改密码成功");
        return AppResult.success();
    }

}
